﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RepositoryUnit.Data.Entity;
using RepositoryUnit.Repository.Interface;
using RepositoryUnit.Repository.UnitOfWork;

namespace RepositoryUnit.Api.Controller
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        private readonly IRepository<Student> _studentRepository;
        private readonly IUnitOfWork _unitOfWork;

        public StudentController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _studentRepository = _unitOfWork.GetRepository<Student>();
        }

        /// <summary>
        /// 创建学生
        /// </summary>
        /// <returns></returns>
        [Route("createStu")]
        [HttpPost]
        public async Task<Student> CreateStu()
        {
            var stu = new Student
            {
                Id = Guid.NewGuid(),
                Age=17,
                Name="史育东"
            };

            await _studentRepository.AddAsync(stu);
            await _unitOfWork.SaveChangesAsync();
            return stu;

        }
        /// <summary>
        /// 查询学生
        /// </summary>
        /// <returns></returns>
        [Route("getStu")]
        [HttpGet]
        public  async Task<IEnumerable<Student>> GetStu()
        {
            var queryable = _studentRepository.Queryable;
            var list2 = queryable.ToList();

            var list3 = await _studentRepository.GetListWithNoTrackingAsync(queryable);

            var list = await _studentRepository.GetAllListWithNoTrackingAsync();
            return list ;
        }

        public static Expression<Func<Student,bool>> GetStudentExpression(string propertyToFilter, string value)
        {
            var stu = Expression.Parameter(typeof(Student));
            var memberAccess = Expression.PropertyOrField(stu, propertyToFilter);
            var exprRight = Expression.Constant(value);
            var equalExpr = Expression.Equal(memberAccess, exprRight);
            Expression<Func<Student, bool>> lambda = Expression.Lambda<Func<Student, bool>>(equalExpr, stu);
            return lambda;
        }

    }
}
